package structuralPatterns.flyweight;

import java.util.HashMap;
import java.util.Map;

class Flyweight {
    private String intrinsicState;

    public Flyweight(String intrinsicState) {
        this.intrinsicState = intrinsicState;
    }

    public void operation(String extrinsicState) {
        // 执行操作，使用内部状态和外部状态
        System.out.println("Intrinsic State: " + intrinsicState + ", Extrinsic State: " + extrinsicState);
    }
}

class FlyweightFactory {
    private Map<String, Flyweight> flyweights = new HashMap<>();

    public Flyweight getFlyweight(String key) {
        if (!flyweights.containsKey(key)) {
            flyweights.put(key, new Flyweight(key));
        }
        return flyweights.get(key);
    }
}

public class FlyweightPattern {
    public static void main(String[] args) {
        FlyweightFactory factory = new FlyweightFactory();
        Flyweight f1 = factory.getFlyweight("state1");
        Flyweight f2 = factory.getFlyweight("state2");
        f1.operation("extrinsicState1");
        f2.operation("extrinsicState2");
        factory.getFlyweight("state1").operation("extrinsicState3");
    }
}
